//
//  Plink.m
//  PezMonkey
//
//  Created by Spence DiNicolantonio on 11/13/09.
//  Copyright 2009 Necrosoft. All rights reserved.
//

#import "Plink.h"

#define kPolygonVerts 5


@implementation Plink

- (NSString *)demoName {
	return @"Plink";
}

/**
 * Initializes the receiver.
 */
- (void)start {
	// create space
	self.space = [PMSpace spaceWithGravity:PMVectMake(0, -0.4)];
	[space setIterations:1];
	[space setActiveHashSize:999 cellDimension:40];
	[space setStaticHashSize:2999 cellDimension:30];
	
	PMBody *body;
	PMShape *shape;
	
	// create vertices for polygon shape
	PMVect polygonVerts[kPolygonVerts];
	for (int i=0; i<kPolygonVerts; i++) {
		PMFloat angle = -2*M_PI*i/((PMFloat) kPolygonVerts);
		PMVect vert = PMVectMake(10 * cos(angle), 
								 10 * sin(angle));
		polygonVerts[i] = vert;
	}
	
	// define vertices for triangles
	NSUInteger triangleVertCount = 3;
	PMVect triangleVerts[3] = {
		PMVectMake(-15,-15),
		PMVectMake(  0, 10),
		PMVectMake( 15,-15),
	};
	
	
	// create shared static body
	PMBody *staticBody = [PMBody staticBody];
	
	// create static triangles
	for (int i=0; i<9; i++) {
		for (int j=0; j<6; j++) {
			PMFloat stagger = ((j % 2) * 40);
			PMVect offset = PMVectMake(i*80 - 320 + stagger, 
									   j*70 - 240);
			shape = [PMPolygonShape polygonShapeWithBody:staticBody
												vertices:triangleVerts
											 vertCount:triangleVertCount 
												  center:offset];
			[shape setElasticity:1.0];
			[shape setFriction:1.0];
			[shape setLayers:PMLayerMaskNotGrabbable];
			[space addShape:shape];
		}
	}
	
	// add lots of polygons
	for (int i=0; i<300; i++) {
		// body
		PMFloat mass = 1.0;
		PMFloat moment = PMMomentForPolygon(mass, polygonVerts, kPolygonVerts, PMVectZero);
		body = [PMBody bodyWithMass:1.0 
							 moment:moment];
		PMFloat x = (random() / (PMFloat) RAND_MAX) * 640 - 320;
		[body setPosition:PMVectMake(x, 350)];
		[space addBody:body];
		
		// shape
		shape = [PMPolygonShape polygonShapeWithBody:body 
											vertices:polygonVerts
										 vertCount:kPolygonVerts];
		[shape setElasticity:0.3];
		[shape setFriction:0.4];
		[space addShape:shape];
	}
}

/**
 * Updates the receiver each frame.
 */
- (void)update:(NSTimeInterval)deltaT {
	for (PMBody *body in [space bodies])
		if(body.position.y < -260) {
			PMFloat x = (random() / (PMFloat) RAND_MAX) * 640 - 320;
			[body setPosition:PMVectMake(x, 260)];
			[body setVelocity:PMVectZero];
		}
}

/**
 * Returns the demo options to be used for the receiver.
 */
- (PMDemoDrawSettings)drawSettings {
	return PMDemoDrawSettingsDefault;
}

@end
